import got from "got";
import { LiveResp } from "../declare/liver";
import * as _ from "lodash";
import { getRedisClient } from "../library/redis";
import { BaseTask } from "./BaseTask";
import { REDIS_KEY } from "../declare/keys";

export class GetLivinglist implements BaseTask {
  runningInterval: NodeJS.Timeout | null = null;
  redisClient = getRedisClient();
  constructor() {
    this.runningInterval = setInterval(this.runTask.bind(this), 5000);
  }
  public async runTask() {
    console.log(new Date(),"running pull list")
    if (this.runningInterval) {
      clearInterval(this.runningInterval);
      this.runningInterval = null;
    }
    const nowLiving = await this.getLivingInfo();
    const nowWatching = (
      await this.redisClient.smembers(REDIS_KEY.REDIS_KEY_NOW_WATCHING_ROOM)
    ).map((id) => {
      return Number(id);
    });
    let unWatching = _.difference(nowLiving, nowWatching);
    if (unWatching.length) {
      await Promise.all(
        unWatching.map(async (roomId) => {
          await this.redisClient.lrem(
            REDIS_KEY.REDIS_QUEUE_NOW_UN_WATCHING_ROOM,
            0,
            roomId
          );
          await this.redisClient.rpush(
            REDIS_KEY.REDIS_QUEUE_NOW_UN_WATCHING_ROOM,
            roomId
          );
        })
      );
    }
    this.runningInterval = setInterval(this.runTask.bind(this), 5000);
  }
  public async getLivingInfo() {
    try {
      const res: {
        body: LiveResp;
      } = await got(
        "https://live.acfun.cn/api/channel/list?count=10000",
        { responseType: "json" }
      );
      if (!res.body.liveList) return [];
      const livingInfo = res.body.liveList.map((e) => {
        return e.authorId;
      });
      return livingInfo;
    } catch (error) {
      console.log(error)
      return []
    }

  }
}
